package com.study.heartBeat;

import com.study.heartBeat.task.ServerHeartBeatTask;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.ScheduledFuture;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: NettyHeartbeatServerHandler
 * @Description:
 * @Date 2024/04/30 11:48
 * @Author songshaoqiu
 **/
public class NettyHeartbeatServerHandler extends SimpleChannelInboundHandler<String> {
    int readTimes =0;
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        readTimes =0;
        System.out.println("读取 【客户端】发送消息："+s);
        channelHandlerContext.writeAndFlush("收到客户端心跳");


    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        ServerHeartBeatTask onlineCoachTask = new ServerHeartBeatTask(channel);
        ScheduledFuture<?> scheduledFuture = channel.eventLoop().next().scheduleAtFixedRate(
                onlineCoachTask, 0, 10, TimeUnit.SECONDS);
        onlineCoachTask.setScheduledFuture(scheduledFuture);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
        switch (idleStateEvent.state()){
            case READER_IDLE:
                readTimes++;
                System.out.println("读超时，超时次数："+readTimes);
                break;
        }
        if (readTimes>3){
            System.out.println("读超时超过3次，关闭连接");
            ctx.writeAndFlush("客户端超时关闭");
            ctx.channel().close();
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("【客户端断开连接】");
    }
}
